package org.idea.qiyu.red.packet.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

import static org.idea.qiyu.red.packet.controller.RedPacketController.sendCount;

/**
 * 初始化红包配置类
 *
 * @Author linhao
 * @Date created in 9:04 下午 2021/11/13
 */
@Configuration
public class InitRedPacketConfig implements InitializingBean {

    /**
     * 250万元 （分单位）
     */
    private static AtomicInteger totalMoney = new AtomicInteger(250 * 10000 * 100);

    /**
     * 拆分为50w个红包
     */
    private static AtomicInteger totalPacketCount = new AtomicInteger(50 * 10000);

    public static short[] packetMoneyArr = new short[totalPacketCount.get()];

    @Override
    public void afterPropertiesSet(){
        System.out.println(" ======== 初始化红包配置 ======== ");
        long beginTime = System.currentTimeMillis();
        while (true){
            if (totalPacketCount.get() > 0) {
                int money = 0;
                if (totalPacketCount.get() == 1) {
                    totalPacketCount.set(0);
                    money = totalMoney.get();
                    break;
                } else {
                    money = ThreadLocalRandom.current().nextInt(0, ((totalMoney.get() / totalPacketCount.get()) * 2));
                    totalMoney.getAndAdd(-1 * money);
                    totalPacketCount.getAndAdd(-1);
                }
                //实际生成的金额使用short类型结构基本就能满足
                packetMoneyArr[totalPacketCount.get()] = (short) money;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗时："+ (endTime - beginTime) + "ms");
        Thread thread = new Thread(new RedPacketWatcher());
        thread.start();
    }


    /**
     * 查看红包的剩余金额线程 （测试使用）
     */
    private class RedPacketWatcher implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.printf("已发出红包数目：%s\n",sendCount.get());
            }
        }
    }
}
